package com.lyl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)//启用 secured注解
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
	@Autowired
	private DataSource dataSource;

	@Override
	protected void configure(HttpSecurity http) throws Exception
		{
			http
					.authorizeRequests()
					.antMatchers("/admin**")
					.hasRole("ADMIN")
					.anyRequest().authenticated()
					.and()
					.formLogin()
					.loginPage("/login")
					.permitAll()
					.and()
					.logout()
					.permitAll()
					.and().csrf().disable();
		}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
		{
			auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(
					"SELECT username,password,true FROM users WHERE username = ?")
					.authoritiesByUsernameQuery("SELECT username,authority FROM "
							+ "authorities WHERE username = ?")
					.passwordEncoder(new Md5PasswordEncoder());
		}

}